package find.prj.lib;

import java.util.HashMap;
import java.util.Set;

public class ParallelFileSearch implements Searcher {

	@Override
	public String getSearchResults(String searchKeyWord, String[] rootPaths, String excludeKeyWord) {
		FileNamesStringArray resultList = new FileNamesStringArray();

		HashMap<Thread, FileSearch> searches = new HashMap<Thread, FileSearch>();

		for(int i=0; i < rootPaths.length; i++) {
			FileSearch fileSearch = new FileSearch(searchKeyWord, rootPaths[i], excludeKeyWord);
			searches.put(new Thread(fileSearch, "Thread " + (i+1)), fileSearch);
		}
		for (Thread thread: searches.keySet())
			thread.start();

		Set<Thread> threads = searches.keySet();
		while (! this.isThreadsFinished(threads)) {
			;
		}

		for (Thread thread: searches.keySet()) {
			resultList.add(FileNamesStringArray.FILTERED_FILE_NAMES_DELIMITER);
			FileNamesStringArray fileNames = searches.get(thread).getFilteredFileNames();
			
			for(int k=0; k < fileNames.size(); k++ )
				fileNames.set(k, thread.getName() + " : " + fileNames.get(k));
			resultList.addAll(fileNames);
			resultList.add(FileNamesStringArray.EXCLUDED_FILE_NAMES_DELIMITER);
			
			fileNames = searches.get(thread).getExcludedFileNames();
			for(int k=0; k < fileNames.size(); k++ )
				fileNames.set(k, thread.getName() + " : " + fileNames.get(k));
			resultList.addAll(fileNames);
		}
		return resultList.toString();
	}
	
	private boolean isThreadsFinished (Set<Thread> threads) {
		boolean threadsFinishedState = true;
		for (Thread thread : threads)
			threadsFinishedState = threadsFinishedState && !(thread.isAlive());
		return threadsFinishedState;
	}
	
	
}